﻿using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.ServiceModel.DomainServices.Client;
using System.Text;
using System.Windows;
using System.Windows.Browser;
using System.Windows.Controls;
using NetBay.Core.BusinessEntities.Historic;
using Rio.Applications.Web.Services;
using Rio.Framework.Localisation;
using Rio.Framework.Pages.AppCode.ApplicationNavigation;
using Rio.Framework.Pages.Context;
using Telerik.Windows;
using Telerik.Windows.Controls.GridView;
using GalaSoft.MvvmLight.Messaging;

namespace Rio.Framework.Pages.Controls.Historic
{
    public partial class ImportHistoric : UserControl, INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        private HistoricInformation _selectedLastIndexations;

        public ObservableCollection<HistoricInformation> LastIndexations { get; set; }

        public HistoricInformation SelectedLastIndexations
        {
            get { return _selectedLastIndexations; }
            set
            {
                _selectedLastIndexations = value;
                OnPropertyChanged("SelectedLastIndexations");

                LastIndexationsDisplayButton.IsEnabled = SelectedLastIndexations != null;
            }
        }

        public int HistoricMaxCountResultsDisplay { get; set; }

        public ImportHistoric()
        {
            InitializeComponent();

            InitLabels();

            LastIndexationsRadGridView.IsBusy = true;

            SettingsDomainContext settingsDomainContext = new SettingsDomainContext();
            settingsDomainContext.GetHistoricMaxCountResultsDisplay(
                delegate(InvokeOperation<int> retr)
                {
                    HistoricMaxCountResultsDisplay = retr.Value;
                    LoadLastIndexations();
                },
                null);

            LastIndexationsRadGridView.AddHandler(GridViewCellBase.CellDoubleClickEvent, new EventHandler<RadRoutedEventArgs>(OnCellDoubleClick), true);
        }

        /// <summary>
        /// Loads the last indexations.
        /// </summary>
        private void LoadLastIndexations(NotificationMessage n = null)
        {
            BusinessEntitiesDomainContext businessEntitiesDomainContext = new BusinessEntitiesDomainContext();
            var query = businessEntitiesDomainContext.GetLastConsultationsQuery(
                Constant.szGetDescription(Constant.UserActions.AJOUT_DOCUMENTS_DOSSIER),
                GlobalWebContext.CurrentUser.UserId,
                HistoricMaxCountResultsDisplay,
                false);

            businessEntitiesDomainContext.Load(
                query,
                delegate(LoadOperation<HistoricInformation> retr)
                {
                    if (retr.Error == null && retr.Entities != null)
                    {
                        LastIndexations = new ObservableCollection<HistoricInformation>(
                            retr.Entities
                            .OrderByDescending(item => item.ActionDate)
                            .ThenByDescending(item => item.ActionTime));

                        OnPropertyChanged("LastIndexations");
                    }

                    LastIndexationsRadGridView.IsBusy = false;
                },
                null);
        }

        /// <summary>
        /// Inits the labels.
        /// </summary>
        private void InitLabels()
        {
            LastIndexationsTabItem.Header = Resx.GetLabel(ResxHistoric.HISTORIC_LAST_INDEXATIONS);
            LastIndexationsDisplayButton.Content = Resx.GetLabel(ResxHistoric.HISTORIC_DISPLAY);
            LastIndexationsRadGridView.Columns["LastIndexationsDateHeader"].Header = Resx.GetLabel(ResxHistoric.HISTORIC_DATE_HEADER);
            LastIndexationsRadGridView.Columns["LastIndexationsHourHeader"].Header = Resx.GetLabel(ResxHistoric.HISTORIC_HOUR_HEADER);
            LastIndexationsRadGridView.Columns["LastIndexationsOrganizationHeader"].Header = Resx.GetLabel(ResxHistoric.HISTORIC_ORGANIZATION_HEADER);
            LastIndexationsRadGridView.Columns["LastIndexationsFolderTypeHeader"].Header = Resx.GetLabel(ResxHistoric.HISTORIC_FOLDERTYPE_HEADER);
            LastIndexationsRadGridView.Columns["LastIndexationsNbIndexedDocsHeader"].Header = Resx.GetLabel(ResxHistoric.HISTORIC_NBINDEXEDDOCS_HEADER);
            LastIndexationsRadGridView.Columns["LastIndexationsItemHeader"].Header = Resx.GetLabel(ResxHistoric.HISTORIC_ITEM_HEADER);
            LastIndexationsRadGridView.Columns["LastIndexationsIndexHeader"].Header = Resx.GetLabel(ResxHistoric.HISTORIC_INDEX_HEADER);
        }

        /// <summary>
        /// Called when [cell double click].
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="args">The <see cref="Telerik.Windows.RadRoutedEventArgs"/> instance containing the event data.</param>
        private void OnCellDoubleClick(object sender, RadRoutedEventArgs args)
        {
            OpenSelectedItem();
        }

        /// <summary>
        /// Handles the Click event of the Open control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.RoutedEventArgs"/> instance containing the event data.</param>
        private void Open_Click(object sender, RoutedEventArgs e)
        {
            OpenSelectedItem();
        }

        /// <summary>
        /// Opens the selected item.
        /// </summary>
        private void OpenSelectedItem()
        {
            if (SelectedLastIndexations != null)
            {
                NavigationHelper.Instance.GetImportLink(SelectedLastIndexations.OrganizationId, SelectedLastIndexations.FolderTypeId, SelectedLastIndexations.Indexes.ToList(), true);
            }
        }

        /// <summary>
        /// Called when [property changed].
        /// </summary>
        /// <param name="propertyName">Name of the property.</param>
        public void OnPropertyChanged(string propertyName)
        {
            if (this.PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }
}
